package vn.appsmobi.loader;

import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONObject;

import vn.appsmobi.loader.BaseResult.ResultStatus;
import vn.appsmobi.model.AppInfo;
import vn.appsmobi.model.ListAppInfo;
import vn.appsmobi.ulti.Constant;
import vn.appsmobi.ulti.Log;
import vn.appsmobi.ulti.Request;
import android.content.Context;
import android.net.Uri;

public class SearchLoader extends BaseLoader
{
	private CharSequence searchKey = "";
	
	
    public SearchLoader(Context paramContext)
    {
        super(paramContext);
    }
    
    public void setsearchKey(CharSequence searchKey2)
    {
        this.searchKey = searchKey2;
    }

    
    protected BaseResult getResultInstance()
    {
        return new Result();
    }
    
    protected BaseLoader.UpdateTask getUpdateTask()
    {
        return new SearchUpdateTask();
        
    }
    
    protected BaseResult parseResult(JSONObject json, BaseResult result)
    throws Exception
    {
    //	Log.v("parseResult.........................");
    	//
        Result localResult = (Result)result;
        if(ListAppInfo.valueOfAray(json).size() > 0 )
        {
        	localResult.mTopAppInfos = ListAppInfo.valueOfAray(json);
        	localResult.setResultStatus(ResultStatus.OK);
        }
   
        return localResult;
    }
    
    private class SearchUpdateTask extends BaseLoader.UpdateTask
    {
        private SearchUpdateTask()
        {
            super();
        }
        
        @Override
        protected Request getRequest() {
            // TODO Auto-generated method stub
        	
        	Log.v("search request:" + String.format(Constant.SEARCH_URL,URLEncoder.encode(SearchLoader.this.searchKey.toString())));
            return new Request(String.format(Constant.SEARCH_URL,URLEncoder.encode(SearchLoader.this.searchKey.toString())));
        }
        
    }
    
    public static final class Result extends BaseResult
    {
        public ArrayList<AppInfo> mTopAppInfos;
        
        protected int getCount()
        {
            int count = 0;
            if (this.mTopAppInfos != null)
            count = this.mTopAppInfos.size();
            return count;
        }
        
        public BaseResult shallowClone()
        {
            Result localResult = new Result();
            localResult.mTopAppInfos = this.mTopAppInfos;
            return localResult;
        }
    }
    
    
}